package com.example.demo.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.demo.bean.CmsArticle;
import com.example.demo.bean.CmsCategory;
import com.example.demo.mapper.CmsArticleMapper;
import com.example.demo.mapper.CmsCategoryMapper;

@Service
public class CmsArticleService {
	@Autowired
	private CmsArticleMapper cmsArticleMapper;
	
	@Autowired
	private CmsCategoryMapper categoryMapper;
	
	public List<CmsArticle> getAllArticles() {
		List<CmsArticle> list = cmsArticleMapper.allArticleWithParent();
		if (list!=null) {
			return list;
		}else {
			return new ArrayList<CmsArticle>();
		}
	}
	
	public boolean saveOrUpdateCmsArticle(CmsArticle cmsArticle) {
		
		String id = cmsArticle.getCategoryId();
		if(id!=null&&!"".equals(id)) {
			CmsCategory cs= categoryMapper.selectByPrimaryKey(cmsArticle.getCategoryId());
			if(cs==null) {
				return false;
			}
		}
		if(cmsArticle.getId()!=null&&!"".equals(cmsArticle.getId())) {
			cmsArticleMapper.updateByPrimaryKey(cmsArticle);
		}else {
			cmsArticle.setId(UUID.randomUUID().toString());
			cmsArticleMapper.insert(cmsArticle);
		}
		return true;
	}
	
	
	public int deleteById(String id) {
		CmsArticle cmsArticle  = cmsArticleMapper.selectByPrimaryKey(id);
		if (cmsArticle ==null) {
			return -1;
		}
		
		if (categoryMapper.selectByPrimaryKey(cmsArticle.getCategoryId())== null) {
			return -2;
		}
		return cmsArticleMapper.deleteByPrimaryKey(id);
	}
	
	public boolean saveOrUpdate(String id,String title,String author, String categoryId) {
		
		if (categoryId!=null && !"".equals(categoryId)) {
			CmsCategory ca = categoryMapper.selectByPrimaryKey(categoryId);
			if (ca==null) {
				return false;
			}
			if (id==null&&"".equals(id)) {
				
				CmsArticle cmsArticle =new CmsArticle();
				
				cmsArticle.setId(UUID.randomUUID().toString());
				cmsArticle.setTitle(title);
				cmsArticle.setMemberName(author);
				cmsArticle.setCategoryId(categoryId);
				cmsArticle.setPublishDate(new Date());
				cmsArticle.setStatus("发布");
				cmsArticle.setReadNum(0);
				cmsArticleMapper.insert(cmsArticle);	
			}else {
				
				CmsArticle cmsArticle = cmsArticleMapper.selectByPrimaryKey(id);
				if (cmsArticle==null) {
					return false;
				}
				cmsArticle.setTitle(title);
				cmsArticle.setCategoryId(categoryId);
				cmsArticle.setMemberName(author);
				cmsArticleMapper.updateByPrimaryKey(cmsArticle);
			}
		}
		
		return true;
	}
	
	public List<CmsArticle> searchBy(
			Date begin,Date end,String key){
		return cmsArticleMapper.selectBy(begin, end, key);
	}
	
	public boolean updateState(String artId,String state) {
		int result = cmsArticleMapper.updateStateById(artId, state);
		//返回结果代表更新的记录条数，如果一条都没有，代表数据不存在。
		if(result==0) { 
			return false;
		}
		return true;
	}
	
	
}
